/**
 * 中间件组合器
 * 用于组合多个中间件
 */

class ComposeMiddleware {
    
    /**
     * 组合中间件
     * @param {Array} middlewares 中间件数组
     * @returns {Function} 组合后的中间件
     */
    static compose(middlewares) {
        if (!Array.isArray(middlewares)) {
            throw new TypeError('Middleware stack must be an array!');
        }
        
        for (const middleware of middlewares) {
            if (typeof middleware !== 'function') {
                throw new TypeError('Middleware must be composed of functions!');
            }
        }
        
        return function(context, next) {
            let index = -1;
            
            function dispatch(i) {
                if (i <= index) {
                    return Promise.reject(new Error('next() called multiple times'));
                }
                index = i;
                
                let middleware = middlewares[i];
                if (i === middlewares.length) {
                    middleware = next;
                }
                
                if (!middleware) {
                    return Promise.resolve();
                }
                
                try {
                    return Promise.resolve(middleware.call(context, dispatch.bind(null, i + 1)));
                } catch (err) {
                    return Promise.reject(err);
                }
            }
            
            return dispatch(0);
        };
    }
    
    /**
     * 创建中间件包装器
     * @param {Function} handler 业务处理函数
     * @param {Array} middlewares 中间件数组
     * @returns {Function} 包装后的函数
     */
    static createMiddlewareWrapper(handler, middlewares) {
        const composed = this.compose(middlewares);
        
        return async function(...args) {
            const context = this;
            
            // 执行中间件链
            await composed(context, async () => {
                // 所有中间件通过后执行业务逻辑
                return handler.apply(context, args);
            });
            
            return context.result || { code: 500, message: '处理失败', data: null };
        };
    }
}

module.exports = { ComposeMiddleware };